package util

import (
	"github.com/go-sql-driver/mysql"
	"time"
)

type MysqlConnOption struct {
	Dsn         string
	Addr        string
	DbName      string
	MaxOpen     int
	MaxIdle     int
	MaxIdleTime time.Duration
	MaxLifetime time.Duration
}

func NewMysqlConnOption(
	dsn string,
	maxOpen, maxIdle int,
	maxIdleTime, maxLifeTime time.Duration,
) (*MysqlConnOption, error) {
	addr := ""
	dbName := ""
	if cfg, err := mysql.ParseDSN(dsn); err != nil {
		return nil, err
	} else if cfg.Addr == "" || cfg.DBName == "" {
		return nil, ErrMysqlWrongDsn
	} else {
		addr = cfg.Addr
		dbName = cfg.DBName
	}
	if maxOpen <= 0 {
		maxOpen = NumCPU()*2 + 1
	}
	if maxIdle <= 0 {
		maxIdle = maxOpen / 2
		if maxIdle < 2 {
			maxIdle = 2
		}
	}
	if maxIdleTime < 0 {
		maxIdleTime = 3 * time.Minute
	}
	if maxLifeTime < 0 {
		maxLifeTime = 30 * time.Minute
	}
	return &MysqlConnOption{
		Dsn:         dsn,
		Addr:        addr,
		DbName:      dbName,
		MaxOpen:     maxOpen,
		MaxIdle:     maxIdle,
		MaxIdleTime: maxIdleTime,
		MaxLifetime: maxLifeTime,
	}, nil
}
